<template>
    <div>
        <!-- 
            on-change	文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用	function(file, fileList)
            auto-upload	是否在选取文件后立即进行上传	boolean	—	true
            limit	最大允许上传个数	number
            file-list	上传的文件列表, 例如: [{name: 'food.jpg', url: 'https://xxx.cdn.com/xxx.jpg'}]	array
        -->
        <el-dialog :title="goodstatus.isAdd ? '添加商品' : '编辑商品'" center :visible.sync="goodstatus.isShow"
            :before-close="cancel" @opened="createEdit">
            <el-form :model="goodsform" ref="goodRef" :rules="rules">
                <el-form-item label="一级分类" :label-width="formLabelWidth" prop="first_cateid">
                    <el-select @change="changeSort(false)" v-model="goodsform.first_cateid" placeholder="请选择">
                        <el-option v-for="item in sortlist" :label="item.catename" :value="item.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="二级分类" :label-width="formLabelWidth" prop="second_cateid">
                    <el-select v-model="goodsform.second_cateid" placeholder="请选择">
                        <el-option v-for="item in sortArr" :key="item.id" :label="item.catename"
                            :value="item.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="商品名称" :label-width="formLabelWidth" prop="goodsname">
                    <el-input v-model="goodsform.goodsname" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="价格" :label-width="formLabelWidth" prop="price">
                    <el-input v-model="goodsform.price" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="市场价格" :label-width="formLabelWidth" prop="market_price">
                    <el-input v-model="goodsform.market_price" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="图片" :label-width="formLabelWidth">
                    <el-upload v-model="goodsform.img" :file-list="filelist" action="#" :limit="1" :auto-upload="false"
                        list-type="picture-card" :on-preview="onPreview" :on-change="changeImg">
                        <i class="el-icon-plus"></i>
                    </el-upload>
                    <el-dialog :visible.sync="dialogVisible">
                        <img width="100%" :src="dialogImageUrl" alt="">
                    </el-dialog>
                </el-form-item>
                <el-form-item label="商品规格" :label-width="formLabelWidth" prop="specsid">
                    <el-select @change="changespecs(false)" v-model="goodsform.specsid" placeholder="请选择">
                        <el-option v-for="item in specslist" :label="item.specsname" :key="item.id"
                            :value="item.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="商品属性" :label-width="formLabelWidth" prop="specsattr">
                    <el-select multiple v-model="goodsform.specsattr" placeholder="请选择">
                        <el-option v-for="item in specsArr" :key="item" :label="item" :value="item"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="是否新品" :label-width="formLabelWidth">
                    <el-radio v-model="goodsform.isnew" :label="1">是</el-radio>
                    <el-radio v-model="goodsform.isnew" :label="2">否</el-radio>
                </el-form-item>
                <el-form-item label="是否热卖" :label-width="formLabelWidth">
                    <el-radio v-model="goodsform.ishot" :label="1">是</el-radio>
                    <el-radio v-model="goodsform.ishot" :label="2">否</el-radio>
                </el-form-item>
                <el-form-item label="状态" :label-width="formLabelWidth">
                    <el-switch v-model="goodsform.status" active-color="#13ce66" inactive-color="#ff4949" :active-value="1"
                        :inactive-value="2">
                    </el-switch>
                </el-form-item>
                <el-form-item label="商品描述" :label-width="formLabelWidth">
                    <div id="edit"></div>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="cancel">取 消</el-button>
                <el-button type="primary" @click="confirm">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<script>
/* 
我们在这个商品管理中使用一个简单的富文本编辑器 ，叫 wangeditor
官网：https://www.wangeditor.com/
下载命令 ： npm  install wangeditor
+ wangeditor@4.7.15
基本使用：
1、引入
import E from 'wangeditor'
2、使用，创建界面
new E('DOM节点')
new E('DOM节点').create()
初始化
new E('DOM节点').txt.html('要赋值的内容')
取值
new E('DOM节点').txt.html()
销毁富文本
new E('DOM节点').destroy()
*/
import { goodsadd, goodsinfo, goodsedit } from '../../request/api'
import { mapGetters, mapActions } from 'vuex'
import E from 'wangeditor'
export default {
    props: ['goodstatus'],
    data() {
        return {
            content: null,
            editorOption: {},
            goodsform: {
                first_cateid: '',//一级分类编号
                second_cateid: '',//二级分类编号
                goodsname: '',//商品名称
                price: '',//商品价格
                market_price: "",//市场价格
                img: '',//商品图片（文件）
                description: '',//商品描述
                specsid: '',//商品规格编号
                specsattr: '',//商品规格属性
                isnew: 1,//是否新品 1-是 2-否
                ishot: 1,//是否热卖推荐 1-是 2-否
                status: 1,//状态1正常2禁用
            },
            formLabelWidth: '80px',
            dialogImageUrl: '',
            dialogVisible: false,
            rules: {
                goodsname: [
                    { required: true, message: '请输入活动名称', trigger: 'blur' },
                    { min: 2, max: 7, message: '长度在 2 到 7 个字符', trigger: 'blur' }
                ],
                price: [
                    { required: true, message: '价格不能为空' },
                ],
                market_price: [
                    { required: true, message: '价格不能为空' },
                ],
                first_cateid: [
                    { required: true, message: '请选择活动区域', trigger: 'change' }
                ],
                second_cateid: [
                    { required: true, message: '请选择活动区域', trigger: 'change' }
                ],
                specsid: [
                    { required: true, message: '请选择活动区域', trigger: 'change' }
                ],
                specsattr: [
                    { required: true, message: '请选择活动区域', trigger: 'change' }
                ],

            },
            sortArr: [],//二级分类
            specsArr: [],//规格属性
            filelist: [],//图片清空
            edit: null
        }
    },
    methods: {
        createEdit() {
            // 创建界面
            this.edit = new E('#edit')
            this.edit.create()
            // 初始化
            this.edit.txt.html(this.goodsform.description)
        },
        // 选择一级分类显示二级分类
        changeSort(n) {
            // 切换分类时通过对应的下标找到children
            let index = this.sortlist.findIndex((item) => item.id === this.goodsform.first_cateid)
            this.sortArr = this.sortlist[index].children
            if (!n) {
                // 点击切换时清除二级分类的内容
                this.goodsform.second_cateid = ''
            }

        },
        // 选择商品规格
        changespecs(n) {
            let index = this.specslist.findIndex((item) => item.id === this.goodsform.specsid)
            this.specsArr = this.specslist[index].attrs
            if (!n) {
                // 切换时清除规格属性的内容
                this.goodsform.specsattr = ''
            }


        },
        ...mapActions({
            getSort: 'sort/GetSortInfo',
            getSpecs: 'specs/GetSpecsInfo',
            getGoods: 'goods/GetGoodsInfo',
            getCount: 'goods/GetCountInfo'
        }),
        // 点击取消关闭弹框
        cancel() {
            this.$emit('cancel', false)
            this.reset()
        },
        // 重置表单
        reset() {
            this.goodsform = {
                first_cateid: '',//一级分类编号
                second_cateid: '',//二级分类编号
                goodsname: '',//商品名称
                price: '',//商品价格
                market_price: "",//市场价格
                img: '',//商品图片（文件）
                description: '',//商品描述
                specsid: '',//商品规格编号
                specsattr: '',//商品规格属性
                isnew: 1,//是否新品 1-是 2-否
                ishot: 1,//是否热卖推荐 1-是 2-否
                status: 1,//状态1正常2禁用
            },
                // 清除图片
                this.filelist = []
            // 清除校验规则
            this.$refs.goodRef.resetFields()
            // 销毁
            this.edit.destroy()
        },
        // 数据回显
        lookup(id) {
            goodsinfo({ id })
            .then(res => {
                if (res.code == 200) {
                    this.$message.success(res.msg)
                    this.goodsform = res.list
                    this.goodsform.id = id
                    this.filelist = this.goodsform.img ? [{ url: this.goodsform.img }] : []
                    this.goodsform.specsattr = this.goodsform.specsattr.split(',')
                    // 如果是编辑回显时不需要清除二级分类和规格属性
                    this.changeSort(true)
                    this.changespecs(true)
                    this.edit.txt.html(this.goodsform.description)
                } else {
                    this.$message.error(res.msg)
                }
            })
        },
        // 点击确认添加或者编辑
        confirm() {
            this.$refs.goodRef.validate((val) => {
                if (val) {
                    this.goodsform.specsattr = this.goodsform.specsattr.join(',')
                    this.goodsform.description = this.edit.txt.html()
                    if (this.goodstatus.isAdd) {//添加
                        goodsadd(this.goodsform)
                            .then(res => {
                                if (res.code == 200) {
                                    this.$message.success(res.msg)
                                    this.getCount()
                                    this.getGoods()
                                    this.cancel()
                                } else {
                                    this.$message.success(res.msg)
                                }
                            })
                    } else {//编辑
                        goodsedit(this.goodsform)
                            .then(res => {
                                if (res.code == 200) {
                                    this.$message.success(res.msg)
                                    this.getCount()
                                    this.getGoods()
                                    this.cancel()
                                } else {
                                    this.$message.success(res.msg)
                                }
                            })
                    }
                }
            })
        },
        // 图片视图
        onPreview(file) {
            this.dialogVisible = true
            this.dialogImageUrl = file.url
        },
        // 图片上传
        changeImg(file, fileList) {
            this.goodsform.img = file.raw
        }
    },
    mounted() {
        this.$store.dispatch('sort/GetSortInfo')
        this.$store.dispatch('specs/GetSpecsInfo')
    },
    watch: {},
    computed: {
        ...mapGetters({
            sortlist: 'sort/getSort',
            specslist: 'specs/getSpecs',
            goodslist: 'goods/getGoods'
        })
    },
    filters: {},
}
</script>
<style scoped></style>